<template>
    <div>
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>MQTT</span>
            </div>
            <div>
                <ul>
                    <li v-for="(item, i) in messageList" :key="i">
                        <span>{{ item }}</span>
                    </li>
                </ul>
            </div>
        </el-card>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { SaveSent, EmailInfo, SaveDraft } from '@/api/extend/email'
import mqtt from 'mqtt'

// 连接选项
const options = {
    clean: true, // true: 清除会话, false: 保留会话
    connectTimeout: 4000, // 超时时间
    // 认证信息
    clientId: `Cassandra_${Date.now()}`,
    username: 'fbssys',
    password: 'Cassandra123',
}
const topic = "agv/battery/status/1";
// 连接字符串, 通过协议指定使用的连接方式
// ws 未加密 WebSocket 连接
// wss 加密 WebSocket 连接
// mqtt 未加密 TCP 连接
// mqtts 加密 TCP 连接
// wxs 微信小程序连接
// alis 支付宝小程序连接
const connectUrl = 'ws://FBS.Sys.Node21:8083/mqtt'

export default {
    created()
    {
        const client = mqtt.connect(connectUrl, options)

        client.on('connect', function ()
        {
            client.subscribe(topic, function (err)
            {
                if (!err)
                {
                    client.publish(topic, 'Hello mqtt')
                }
            });
        });

        client.on('reconnect', (error) =>
        {
            this.clearMessage();
            this.messageList.push(`正在重连：${error}`);
            console.log('正在重连：', error)

        })

        client.on('error', (error) =>
        {
            this.clearMessage();
            this.messageList.push(`连接失败：${error}`);
            console.log('连接失败：', error)
        })

        client.on('message', (topic, message) =>
        {
            this.clearMessage();
            this.messageList.push(`收到消息：topic=>${topic} Message=>${message.toString()}`);
            console.log('收到消息：', topic, message.toString())
        })

        //client.subject();
    },
    data()
    {
        return {
            messageList: []
        }
    }, computed: {
        ...mapGetters(['userInfo']),
    },
    methods: {
        clearMessage()
        {
            if (this.messageList.length > 32)
            {
                this.messageList = [];
            }
        },
        sendMessage(type)
        {
            if (!this.textarea)
            {
                return;
            }
            if ("EMail" === type)
            {
                let data = {
                    recipient: this.recipient,
                    subject: this.subject,
                    bodyText: this.textarea,
                    attachment: JSON.stringify([])
                };
                SaveSent(data).then(res =>
                {
                    this.$message({
                        message: res.msg,
                        type: 'success',
                        duration: 1500
                    });
                }).catch((ex) =>
                {
                    this.$message.error("邮件发送错误！");
                    console.error(ex);
                });
            }
            else if ("Weixin" == type)
            {
                let data = {};
                SendWeiXinMessage(data).then(res =>
                {
                    this.$message({
                        message: "微信信息发送成功！",
                        type: 'success',
                        duration: 1500
                    });
                }).catch((ex) =>
                {
                    this.$message.error("微信信息发送错误！");
                    console.error(ex);
                });;
            }
            else
            {
                let socket = this.$store.getters.socket;
                let token = this.$store.getters.token;
                let sendMessage = {
                    method: "SendMessage",
                    toUserId: this.userInfo.userId,
                    messageType: "text",
                    messageContent: `CMD:${type}|${this.textarea}`,
                    token: token,
                }
                socket.send(JSON.stringify(sendMessage));
                this.textarea = `${Date.now()}:Cassandra向您问好!`
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix {
    .left {
        align-items: start;
    }

    .rigth {
        align-items: end;
    }
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

.box-card {
    width: 480px;
}
</style>

